package com.ton.utils.quartz;

import com.ton.context.QuartzContext;
import org.quartz.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * 定时任务Quartz  工具类
 * 用于调度器、触发器 以及任务的 创建、状态修改 移除等
 */
public class QuartzUtils {
// 创建作业调度器工厂

    /**
     * 创建定时任务 定时任务创建之后默认启动状态
     * @param scheduler   调度器
     * @param quartzContext  定时任务信息类
     * @throws Exception
     */
    public static void createScheduleJob(Scheduler scheduler, QuartzContext quartzContext){

        try {
            //获取到定时任务的执行类  必须是类的绝对路径名称
            //定时任务类需要是job类的具体实现 QuartzJobBean是job的抽象类。
            Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(quartzContext.getJobClass());
            JobDataMap jobDataMap = new JobDataMap();
            Map<String, Object> data = quartzContext.getData();
            jobDataMap.putAll(data);

            // 构建定时任务信息
            JobDetail jobDetail = JobBuilder.newJob(jobClass)
                    .withIdentity(quartzContext.getJobName())
                    .usingJobData(jobDataMap)
                    .build();

            // 设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                    .cronSchedule(quartzContext.getCronExpression());

            //设置随机时间 生成 1 到 10 之间的随机整数
            int seconds = new Random().nextInt(10)+1;
            //设置随机延迟时间
            LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(seconds);
            Date from = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());


            // 构建触发器trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(quartzContext.getJobName())
                    .startAt(from) //设置开始时间
                    .withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);

        } catch (ClassNotFoundException e) {
            //抛出异常 方便事务回滚
            throw new RuntimeException("定时任务类路径出错：请输入类的绝对路径");
        } catch (SchedulerException e) {
            throw new RuntimeException("创建定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据任务名称暂停定时任务
     * @param scheduler  调度器
     * @param jobName    定时任务名称
     * @throws SchedulerException
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("暂停定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据任务名称恢复定时任务
     * @param scheduler  调度器
     * @param jobName    定时任务名称
     * @throws SchedulerException
     */
    public static void resumeScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("启动定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据任务名称立即运行一次定时任务
     * @param scheduler     调度器
     * @param jobName       定时任务名称
     * @throws SchedulerException
     */
    public static void runOnce(Scheduler scheduler, String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("运行定时任务出错："+e.getMessage());
        }
    }

    /**
     * 更新定时任务
     * @param scheduler   调度器
     * @param quartzContext  定时任务信息类
     * @throws SchedulerException
     */
    public static void updateScheduleJob(Scheduler scheduler, QuartzContext quartzContext)  {
        try {
            //获取到对应任务的触发器
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzContext.getJobName());
            //设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzContext.getCronExpression());
            //重新构建任务的触发器trigger
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置对应的job
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            System.out.println("更新定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据定时任务名称从调度器当中删除定时任务
     * @param scheduler 调度器
     * @param jobName   定时任务名称
     * @throws SchedulerException
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("删除定时任务出错："+e.getMessage());
        }
    }

}